﻿using Microsoft.Extensions.Logging;
using Naruto.Redis;
using Naruto.Subscribe.Extension;
using Naruto.Subscribe.Interface;
using Naruto.Subscribe.Object;
using Naruto.Subscribe.Provider.Redis.Object;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Naruto.Subscribe.Provider.Redis.Internal
{
    /// <summary>
    /// redis发布 提供者
    /// </summary>
    public class RedisPublish : INarutoPublish
    {
        private readonly ILogger logger;

        private readonly IRedisRepository redis;

        public RedisPublish(ILogger<RedisPublish> _logger, IRedisRepository _redis)
        {
            logger = _logger;
            redis = _redis;
        }

        /// <summary>
        /// 同步发布
        /// </summary>
        /// <param name="subscribeName"></param>
        /// <param name="msg"></param>
        public void Publish(string subscribeName, object msg = null, IDictionary<string, string> headers = default)
        {
            subscribeName.CheckNullOrEmpty();
            logger.LogInformation("Publish:开始发布消息，subscribeName={subscribeName},msg={msg}", subscribeName, msg);
            //转换消息
            var messageModel = BuildMessage(subscribeName, headers, msg);
            //发布消息
            var result = redis.Stream.Add(subscribeName, new Dictionary<string, byte[]>
            {
                { ConstObject.Body,messageModel.ToJsonString().ToByte()}
            });
            logger.LogInformation("Publish:发布完成，subscribeName={subscribeName},messageModel={messageModel},result={res}", subscribeName, messageModel, result);
        }

        /// <summary>
        /// 异步发布
        /// </summary>
        /// <param name="subscribeName"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public async Task PublishAsync(string subscribeName, object msg = null, IDictionary<string, string> headers = default)
        {
            subscribeName.CheckNullOrEmpty();
            logger.LogInformation("PublishAsync:开始发布消息，subscribeName={subscribeName},msg={msg}", subscribeName, msg);

            //转换消息
            var messageModel = BuildMessage(subscribeName, headers, msg);

            //发布消息
            var result = await redis.Stream.AddAsync(subscribeName, new Dictionary<string, byte[]>
            {
                { ConstObject.Body,messageModel.ToJsonString().ToByte()}
            });
            logger.LogInformation("PublishAsync:发布完成，subscribeName={subscribeName},messageModel={messageModel},result={res}", subscribeName, messageModel, result);
        }
        /// <summary>
        /// 构建消息
        /// </summary>
        /// <param name="subscribeName"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        private MessageModel BuildMessage(string subscribeName, IDictionary<string, string> headers, object msg = null)
        {
            return new MessageModel()
            {
                Id = Guid.NewGuid().ToString(),
                Header = headers,
                SubscribeName = subscribeName,
                MessageContent = IsJsonFormat(msg.ToString()) ? msg.ToString() : msg?.ToJsonString()
            };
        }
        /// <summary>
        /// 验证数据是否为json格式
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        private bool IsJsonFormat(string value)
        {
            if (string.IsNullOrWhiteSpace(value))
                return false;
            if ((value.StartsWith("{") && value.EndsWith("}")) ||
                (value.StartsWith("[") && value.EndsWith("]")))
            {
                try
                {
                    var obj = JToken.Parse(value);
                    return true;
                }
                catch (JsonReaderException)
                {
                    return false;
                }
            }
            return false;
        }
    }
}
